package com.example.android_little_game

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import android.view.View
import androidx.core.view.children
import androidx.gridlayout.widget.GridLayout
import com.example.cardgame.model.CardMatchingGame

class ThirdActivity : AppCompatActivity() ,View.OnClickListener{
    lateinit var game: CardMatchingGame
    val cardButtons = mutableListOf<Button>()

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.hide()
        setContentView(R.layout.activity_third)
        val gridLayout = findViewById<GridLayout>(R.id.gridlayout)
        for(v in gridLayout.children){
            if(v is Button) {
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }

        game = CardMatchingGame(cardButtons.count())
        updateUI()  // 修正方法名

        val reset = findViewById<Button>(R.id.button_reset)
        reset.setOnClickListener {
            game = CardMatchingGame(cardButtons.count())
            updateUI()  // 修正方法名
        }

        // 可选：添加返回按钮功能
        val back = findViewById<Button>(R.id.button_back)
        /* 返回按钮点击 */
        findViewById<Button>(R.id.button_back).setOnClickListener {
            saveHighScoreAndExit()
        }

    }

    // 修正方法名：从 uodateUI 改为 updateUI
    fun updateUI(){
        for(button in cardButtons){
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if(card.isChosen) {
                button.text = card.toString()
                button.setBackgroundColor(Color.WHITE)
            }
            else{
                button.text = ""
                button.setBackgroundResource(R.drawable.cartethyia)  // 确保使用正确的drawable名称
            }
        }
        val score = findViewById<TextView>(R.id.scoreTextView)
        score.text = String.format("%s%s",getString(R.string.score),game.score)
    }
    override fun onClick(v:View?){
        if(v is Button){
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }
    /* 系统返回键 */
    override fun onBackPressed() {
        saveHighScoreAndExit()
    }

    /* 工具：保存最高分并退出 */
    private fun saveHighScoreAndExit() {
        // 把当前游戏得分写进单例（仅当创新高）
        if (game.score > PlayerData.highScore) {
            PlayerData.highScore = game.score
        }
        finish()   // 回到 MainActivity
    }
}